<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import {
  permissionAdd,
  permissionFind,
  permissionFindById,
  permissionModify,
  permissionRemove
} from '@/api/system/permission'
import { Modal } from '@arco-design/web-vue'
import { useGlobalStore } from '@/stores/global'

const globalStore = useGlobalStore()
// 搜索表单
const searchForm = reactive({
  // 显示控制
  visible: false,
  // 搜索
  search: () => {
    permissionFind({ pageSize: searchForm.list.pageSize, pageNum: searchForm.list.pageNum }).then((resp) => {
      searchForm.list = resp.data
      searchForm.expandedKeys = searchForm.list.list.map((val: any) => val.id)
    })
  },
  // table 数据
  list: {
    total: 0,
    list: [],
    pageSize: 10,
    pageNum: 1
  },
  expandedKeys: [] as any[]
})


// 操作数据表单
const operationFormRef = ref()
const operationForm = reactive({
  // 弹框标题
  title: '添加权限',
  // 是否显示
  visible: false,
  // 表单
  form: {
    id: null,
    method: '',
    name: '',
    parentId: 0,
    uri: ''
  },
  // 验证
  rules: {
    name: [{ required: true, message: '权限名不能为空' }],
    uri: [{
      validator: (value: any, callback: (error?: string) => void) => {
        if (operationForm.form.parentId == 0) {
          return
        }

        if (value == undefined || (value as string).trim() === '') {
          callback('访问路径不能为空')
          return
        }
      }
    }],
    method: [{
      validator: (value: any, callback: (error?: string) => void) => {
        if (operationForm.form.parentId == 0) {
          return
        }

        if (value == undefined || (value as string).trim() === '') {
          callback('访问路径不能为空')
          return
        }
      }
    }]
  },
  // 打开弹框
  open: (record: any) => {
    operationForm.title = '添加权限'
    operationForm.visible = true
    operationForm.reset()

    // 设置上级id
    if (record) {
      operationForm.form.parentId = record.id
    }

  },
  modify: (record: any) => {
    operationForm.title = '修改权限'
    permissionFindById(record.id).then(resp => {
      operationForm.form = resp.data
      operationForm.visible = true
    })

  },
  remove: (record: any) => {
    Modal.confirm({
      title: '警告！',
      content: `确认删除 [${record.name}] 吗？`,
      onOk: () => {
        permissionRemove(record.id).then(() => {
          operationForm.visible = false
          searchForm.search()
        })
      }
    })
  },
  submit: ({ values, errors }: any) => {
    if (errors) {
      return
    }

    // 修改
    if (values.id) {
      permissionModify(values).then(() => {
          operationForm.visible = false
          searchForm.search()
        }
      )
      return
    }

    // 添加权限
    permissionAdd(values).then(() => {
      operationForm.visible = false
      searchForm.search()
    })
  },
  reset: () => {
    operationForm.form = {
      id: null,
      method: '',
      name: '',
      parentId: 0,
      uri: ''
    }
  }
})

onMounted(() => {
  searchForm.search()
  document.title = 'Rocc管理系统 权限管理'
})

</script>

<template>
  <div class="w-full h-full">
    <div class="flex justify-between mr-1">
      <a-space wrap>
        <a-button type="primary" @click="operationForm.open">
          <template #icon>
            <icon-plus />
          </template>
          添加权限
        </a-button>
        <a-button>
          <template #icon>
            <icon-download />
          </template>
          导出权限
        </a-button>
      </a-space>
      <a-space>
        <a-tooltip content="刷新列表" position="tr">
          <a-button size="small" shape="circle" @click="searchForm.search">
            <template #icon>
              <icon-refresh />
            </template>
          </a-button>
        </a-tooltip>
      </a-space>
    </div>
    <a-drawer v-model:visible="operationForm.visible" :title="operationForm.title" :width="500" :footer="false">
      <a-form ref="operationFormRef" :model="operationForm.form" :rules="operationForm.rules"
              @submit="operationForm.submit">
        <a-form-item label="上级URI" field="parentId" validate-trigger="blur">
          <a-select v-model="operationForm.form.parentId">
            <a-option :value="0">无上级</a-option>
            <a-option v-for="(v,k) of globalStore.global.caches.database.parentPermission" :key="k" :label="v"
                      :value="Number(k)" />
          </a-select>
        </a-form-item>
        <a-form-item label="权限名称" field="name" validate-trigger="blur" hide-asterisk>
          <a-input v-model="operationForm.form.name" />
        </a-form-item>
        <a-form-item label="访问路径" field="uri" validate-trigger="blur">
          <a-input v-model="operationForm.form.uri" :disabled="operationForm.form.parentId === 0" />
        </a-form-item>
        <a-form-item label="操作类型" field="method" validate-trigger="blur">
          <a-select v-model="operationForm.form.method" :disabled="operationForm.form.parentId === 0">
            <a-option value="GET">GET</a-option>
            <a-option value="POST">POST</a-option>
            <a-option value="DELETE">DELETE</a-option>
            <a-option value="PUT">PUT</a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">
            提交
          </a-button>
        </a-form-item>
      </a-form>
    </a-drawer>

    <a-table row-key="id" :data="searchForm.list.list" expandable :pagination="false"
             v-model:expanded-keys="searchForm.expandedKeys">
      <template #columns>
        <a-table-column title="ID" data-index="id"></a-table-column>
        <a-table-column title="权限名称" data-index="name"></a-table-column>
        <a-table-column title="权限路径" data-index="uri"></a-table-column>
        <a-table-column title="操作类型" data-index="method"></a-table-column>
        <a-table-column title="操作" width="160">
          <template #cell="{record}">
            <a-space>
              <a-button type="text" size="mini" status="warning" @click="operationForm.modify(record)">
                <template #icon>
                  <icon-edit />
                </template>
                修改
              </a-button>
              <a-button type="text" size="mini" status="success" @click="operationForm.open(record)"
                        v-show="!record.parentId">
                <template #icon>
                  <icon-edit />
                </template>
                添加子权限
              </a-button>
              <a-button type="text" status="danger" size="mini" @click="operationForm.remove(record)">
                <template #icon>
                  <icon-delete />
                </template>
                删除
              </a-button>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>
    <div class="mt-4 flex justify-end">
      <a-pagination v-model:current="searchForm.list.pageNum"
                    v-model:page-size="searchForm.list.pageSize"
                    :total="searchForm.list.total"
                    @change="searchForm.search"
                    show-total
                    show-jumper
                    show-page-size
      ></a-pagination>
    </div>
  </div>
</template>

<style scoped>

</style>
